package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"jd.com-user-system/models/mysql"
	"jd.com-user-system/models/redis"
	"jd.com-user-system/userrpc/internal/svc"
	"jd.com-user-system/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *userrpc.UpdateRequest) (*userrpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line

	//图片
	code := in.CaptchaCode
	//itoa := strconv.Itoa(int(in.Id))
	get := redis.Rdb.Get("captchaUpdate")
	if get.Val() != code {
		return nil, fmt.Errorf("验证码输入错误请重新填写")
	}

	//短信
	smsCode := in.SmsCode
	cmd := redis.Rdb.Get("sendSmsUpdate")
	if cmd.Val() != smsCode {
		return nil, fmt.Errorf("短信验证码输入错误请重新填写")
	}

	user := mysql.User{
		Model:       gorm.Model{ID: uint(in.Id)},
		Img:         in.Img,
		AccountName: in.AccountName,
		NickName:    in.Nickname,
		Sex:         in.Sex,
		Data:        in.Data,
	}
	err := mysql.Db.Debug().Model(&user).Updates(&user).Error
	if err != nil {
		return nil, fmt.Errorf("修改失败")
	}
	redis.Rdb.Del("captchaUpdate")
	redis.Rdb.Del("sendSmsUpdate")
	return &userrpc.UpdateResponse{Id: int64(user.ID)}, nil
}
